package sostats.core.datasource;

import java.util.List;

import sostats.core.base.SummaryType;

public class SqlBuilder {
	private Template template;
	private StringBuilder res;
	private SqlBuilder(Template template){
		this.template = template;
		this.res = new StringBuilder();
	}
	public static String build(Template template){
		SqlBuilder sql = new SqlBuilder(template);
		return sql.select().from().groupBy().build();
	}
	private SqlBuilder select(){
		SummaryType summaryType = template.getSummaryType();
		String summary = template.getSummaryValue();
		List<String> categories = template.getCategoryValues();
		res.append("select "+summaryType.toString()+"("+summary+") ");
		for(String category:categories){
			res.append(", ").append(category+" ");
		}
		return this;
	}
	private SqlBuilder from(){
		String tables = template.getJoiningTableValues();
		res.append("from "+tables+" ");
		return this;
	}
	private SqlBuilder groupBy(){
		res.append("group by");
		String part =res.subSequence(res.indexOf("select"),res.indexOf("from")).toString();
		res.append(part.substring(part.indexOf(",")+1));
		return this;
	}
	private String build(){
		return res.toString();
	}
}
